package com.hebeiboruan.controller.system;
import com.hebeiboruan.power.service.PowerService;
import com.hebeiboruan.entity.DTO.system.SearchPowerDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hebeiboruan.power.listener.PowerListener;
import com.hebeiboruan.entity.system.Power;
import com.hebeiboruan.common.HttpMessage;
import com.hebeiboruan.common.exception.CommonException;
import java.time.LocalDateTime;
import com.hebeiboruan.common.exception.ServiceResultEnum;

import javax.servlet.http.HttpServletRequest;
import com.alibaba.excel.EasyExcel;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hebeiboruan.common.uitl.LoggerUtil;
@RestController
@RequestMapping("/power")
public class PowerController {
    private static Logger log = LoggerFactory.getLogger(PowerController.class);
    private PowerService powerService;
    @Autowired
    public void setPowerService(PowerService powerService) {
    this.powerService = powerService;
    }

    @GetMapping("/getAllPower/{page}/{limit}")
    public HttpMessage getAllPower(@PathVariable Integer page,@PathVariable Integer limit){
      HttpMessage.isBlank(page,limit);
        return HttpMessage.data(powerService.page(new Page<>(page,limit)));
    }

    @PostMapping("/searchPower")
    public HttpMessage searchUser(SearchPowerDTO search){
   HttpMessage.isBlank(search.getPage(),search.getLimit());
    QueryWrapper<Power> wrapper=new QueryWrapper<>();
        if (search.getPowerNo() != null) {
        wrapper.like("power_no",search.getPowerNo());
        }
        if (search.getPowerName() != null) {
        wrapper.like("power_name",search.getPowerName());
        }
        if (search.getPowerPath() != null) {
        wrapper.like("power_path",search.getPowerPath());
        }
    return HttpMessage.data(powerService.page(new Page<>(search.getPage(),search.getLimit()),wrapper));
    }
    @PutMapping("/addPower")
    public HttpMessage addPower(Power power, HttpServletRequest request){
       HttpMessage.isBlank( power.getPowerName());
        try {
            powerService.save(power);
            return HttpMessage.result(ServiceResultEnum.INSERT_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.INSERT_ERROR,e);
        }
    }
    @PostMapping("/editPower")
    public HttpMessage editPower(Power power, HttpServletRequest request){
        HttpMessage.isBlank( power.getPowerName());
        try {
            powerService.updateById(power);
            return HttpMessage.result(ServiceResultEnum.UPDATE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.UPDATE_ERROR,e);
        }
    }
    @DeleteMapping("/removePower/{powerNo}")
    public HttpMessage removePower(@PathVariable Integer powerNo,HttpServletRequest request){
       HttpMessage.isBlank(powerNo);
        try {
            powerService.removeById(powerNo);
            return HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.REMOVE_ERROR,e);
        }

    }
    @DeleteMapping("/batchRemovePower/{id}")
    public HttpMessage batchRemovePower(@PathVariable String id){
        HttpMessage.isBlank(id);
        try{
            powerService.removeBatchByIds(Arrays.asList(id.split(",")));
            return HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            throw new CommonException(ServiceResultEnum.BATCH_REMOVE_ERROR,e);
        }

    }

    @PostMapping("/batchAddPower")
    public HttpMessage batchAddPower(@RequestParam("power")List<MultipartFile> power) {
        power.forEach(file->{
                try {
                    EasyExcel.read(file.getInputStream(), Power.class, new PowerListener(powerService)).sheet().doRead();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        return HttpMessage.result(ServiceResultEnum.BATCH_INSERT_TRUE);
    }
        
    @PostMapping("/batchOutPower")
    public void batchOutPower(@RequestParam("power") List<String> power, HttpServletResponse response) throws IOException {
        try{
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //防止乱码
        String fileName ="D:/"+ URLEncoder.encode("powerData:"+LocalDateTime.now().toString(), "UTF-8").replaceAll("\\+", "%20")+".xlsx";
        List<Power> powerData=new ArrayList<>();
            power.forEach(item->{
                try {
                    powerData.add( new ObjectMapper().readValue(item,Power.class));
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            });
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

                EasyExcel.write(response.getOutputStream(), Power.class).autoCloseStream(Boolean.FALSE).sheet("数据").doWrite(powerData);

        }catch (Exception e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            response.getWriter().println(HttpMessage.result(ServiceResultEnum.BATCH_OUT_ERROR));
        }
    }
}


